package com.example.demo.controller

import com.example.demo.pojo.BookInf
import com.example.demo.pojo.ConfigStu
import com.example.demo.pojo.Stu
import com.example.demo.service.BookInfService
import com.example.demo.service.MyService
import com.example.demo.utils.JsonResult
import com.example.demo.utils.MyAsyncTask
import lombok.extern.slf4j.Slf4j
import org.slf4j.Logger
import jakarta.websocket.Session
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.web.bind.annotation.*
import org.springframework.web.multipart.MultipartFile
import java.io.File
import java.time.Instant

@RequestMapping("test")
@RestController
@Slf4j
class MyController {

    companion object {
        var tempSession: Session? = null
    }

    @Autowired
    private lateinit var stu: Stu

    @Autowired
    private lateinit var configStu: ConfigStu

    @Autowired
    private lateinit var log: Logger

    @Autowired
    private lateinit var bookInfService: BookInfService

    @Autowired
    private lateinit var myService: MyService

    @Autowired
    private lateinit var myAsyncTask: MyAsyncTask

    @GetMapping("get")
    fun getHello(@RequestParam("name") name: String, @RequestParam("age") age: Int): String {
        log.info("name : $name  age : $age")
        return "Get Hello $author"
    }

    @GetMapping("websocket")
    fun sendSocket(@RequestParam("msg") msg: String): String {
        tempSession?.basicRemote?.sendText(msg)
        return "sendSocket"
    }

    @PostMapping("create")
    fun createHello(@RequestBody map: Map<String, String>): JsonResult {
        if (map.containsKey("price") && map.containsKey("title")) {
            val book = BookInf().apply {
                price = map["price"]
                title = map["title"]
            }
            bookInfService.save(book)
            return JsonResult.success(data = book)
        }

        return JsonResult.fail("参数错误")
    }

    @PutMapping("update")
    fun updateHello(): String {
        return "update Hello"
    }

    @DeleteMapping("delete")
    fun deleteHello(): String {
        return "delete Hello"
    }

    @Value("\${Custom.properties.author}")
    private var author = ""

    @GetMapping("author")
    fun getAuthor(): JsonResult {
//        val book = bookInfService.getById(1)
//        val book = myService.getBooks()?.get(0)
//        if (book != null) {
//            log.info("${book.title} ${book.price}")
//        } else {
//            log.info("book is null")
//        }
        myAsyncTask.doAsyncTask()
        log.info("getAuthor  " + Thread.currentThread().name)
        return JsonResult.success()
    }

    //上传文件
    @PostMapping("upload")
    fun saveFile(file: MultipartFile): JsonResult {
        file.transferTo(File("E:\\upload", "" + Instant.now().toEpochMilli() + file.originalFilename))
        return JsonResult.success("上传成功")
    }
}
